package blue.webserver;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import blue.logger.Subscriber;
import blue.logger.JsonTransform;

public class CommandListHandler implements HttpHandler{
	Subscriber conn_;

	public CommandListHandler(Subscriber conn) {
		conn_ = conn;
	}
	
	@Override
	public void handle(HttpExchange exchange) throws IOException {
		// Wait for its response
		ArrayList<String> list = readCommandList();
		String list_json = JsonTransform.toJson(list);
        exchange.sendResponseHeaders(200, 0);
        OutputStream os = exchange.getResponseBody();
        os.write(list_json.getBytes());
        os.close();
	}

	private ArrayList<String> readCommandList(){
		ArrayList<String> list = new ArrayList<String>();
		while(true) {
			String recv_json = conn_.recv();
			if (recv_json==null) break;
			list.add(recv_json);
		}
		return list;
	}
}